package com.ddxcloud.common.utils;

import cn.hutool.crypto.SecureUtil;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Map;
import java.util.TreeMap;

public class SignUtil {

	public static String getSign(Map<String, Object> params, String secret) {
		// 移除sign参数
		params.remove("sign");
		StringBuilder sb = new StringBuilder();
		// 将参数以参数名的字典升序排序
		Map<String, Object> sortParams = new TreeMap<>(params);
		// 遍历排序的字典,并拼接"key=value"格式
		for (Map.Entry<String, Object> entry : sortParams.entrySet()) {
			String key = entry.getKey();
			if (ObjectUtils.isNotEmpty(entry.getValue())) {
				String value = entry.getValue().toString();
				sb.append("&").append(key).append("=").append(value);
			}
		}
		String stringA = sb.toString().replaceFirst("&", "");
		String stringSignTemp = stringA + "&" + "appkey=" + secret;
		// 将签名使用MD5加密并全部字母变为大写
		return SecureUtil.md5(stringSignTemp);
	}

	public static boolean verify(String sign1, String sign2) {
		if (sign1.equals(sign2)) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
}
